//
//  HEAddBindUserViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/5/5.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEAddBindUserViewController.h"
#import "HEBindInputCell.h"
#import "HEBindSelectCell.h"

@interface HEAddBindUserViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *formArrs;

@end

@implementation HEAddBindUserViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = KWhiteColor;
    
    self.title = @"添加老人";
    [self.view addSubview:self.tableView];
  
    [self initFooterView];
    [self initCell];
}

#pragma mark -
- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];

    NSMutableArray *classArr = [NSMutableArray array];
    
    NSString *mzStr = @"汉族、蒙古族、回族、藏族、维吾尔族、苗族、彝族、壮族、布依族、朝鲜族、满族、侗族、瑶族、白族、土家族、哈尼族、哈萨克族、傣族、黎族、僳僳族、佤族、畲族、高山族、拉祜族、水族、东乡族、纳西族、景颇族、柯尔克孜族、土族、达斡尔族、仫佬族、羌族、布朗族、撒拉族、毛南族、仡佬族、锡伯族、阿昌族、普米族、塔吉克族、怒族、乌孜别克族、俄罗斯族、鄂温克族、德昂族、保安族、裕固族、京族、塔塔尔族、独龙族、鄂伦春族、赫哲族、门巴族、珞巴族、基诺族";

    // 手机号码
    GDFiterCellModel *phoneModel = [GDFiterCellModel new];
    phoneModel.cellKlass = HEBindInputCell.class;
    phoneModel.keyboardType = UIKeyboardTypePhonePad;
    phoneModel.leftTitle = @"手机号码";
    phoneModel.tableKey = @"bd_phone";
    phoneModel.placeHolder = @"请输入手机号";

    // 姓名
    GDFiterCellModel *nameModel = [GDFiterCellModel new];
    nameModel.cellKlass = HEBindInputCell.class;
    nameModel.leftTitle = @"姓名";
    nameModel.tableKey = @"bd_name";
    nameModel.placeHolder = @"请输入姓名";

    // 地址
    GDFiterCellModel *idModel = [GDFiterCellModel new];
    idModel.cellKlass = HEBindInputCell.class;
    idModel.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    idModel.leftTitle = @"身份证号";
    idModel.tableKey = @"bd_idNo";
    idModel.placeHolder = @"请输入身份证号";

    // 详细地址
    GDFiterCellModel *addrDetailsModel = [GDFiterCellModel new];
    addrDetailsModel.cellKlass = HEBindInputCell.class;
    addrDetailsModel.leftTitle = @"现住址";
    addrDetailsModel.tableKey = @"bd_address";
    addrDetailsModel.placeHolder = @"请输入省市区。精确到门牌号";

    // 民族
    GDFiterCellModel *mzModel = [GDFiterCellModel new];
    mzModel.cellKlass = HEBindSelectCell.class;
    mzModel.leftTitle = @"民族";
    mzModel.tableKey = @"bd_mz";
    mzModel.placeHolder = @"请选择民族";
    mzModel.pickerDataArray =  [mzStr componentsSeparatedByString:@"、"];

    // 关系
    GDFiterCellModel *gxModel = [GDFiterCellModel new];
    gxModel.cellKlass = HEBindInputCell.class;
    gxModel.leftTitle = @"关系";
    gxModel.tableKey = @"bd_gx";
    gxModel.placeHolder = @"请输入你们的关系";

    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[nameModel, mzModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    _sections = @[phoneModel, nameModel, idModel, addrDetailsModel, mzModel, gxModel].mutableCopy;

    [_tableView reloadData];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)initFooterView {
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
    
    // 保存按钮
    QMUIFillButton *saveBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    saveBtn.titleLabel.font = DYFont(16);
    [saveBtn setBackgroundColor:CNavBgColor];
    [saveBtn setTitle:@"保 存" forState:UIControlStateNormal];
    [footerView addSubview:saveBtn];
    [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView).mas_offset(30);
        make.left.equalTo(footerView).mas_offset(50);
        make.right.equalTo(footerView).mas_offset(-50);
        make.height.mas_offset(40);
    }];
  
    self.tableView.tableFooterView = footerView;
}


- (void)saveClick {
    // 判断手机号格式是否正确
    if (![WOValidate valiMobile: self.formModel.bd_phone]) {
         [Dialog toast:@"请输入正确的手机号码" delay:2];
        return;
    }
    
    // 不能绑定自己
    if ([self.formModel.bd_phone isEqualToString:[UserManager sharedUserManager].curUserInfo.username]) {
         [Dialog toast:@"不能输入自己的手机号码" delay:2];
        return;
    }
     
    if ([DYTools isBlankString: self.formModel.bd_name]) {
        [Dialog toastBottom:@"请输入姓名"];
        return;
    }
    
    if (![WOValidate isValidateIdentity: self.formModel.bd_idNo]) {
         [Dialog toast:@"身份证号格式错误" delay:2];
        return;
    }
    
    if ([DYTools isBlankString: self.formModel.bd_address]) {
        [Dialog toastBottom:@"请输入省市区。精确到门牌号"];
        return;
    }
    
    if ([DYTools isBlankString: self.formModel.bd_mz]) {
        [Dialog toastBottom:@"请选择民族"];
        return;
    }
    
    if ([DYTools isBlankString: self.formModel.bd_gx]) {
        [Dialog toastBottom:@"请输入你们的关系"];
        return;
    }
    
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:self.formModel.bd_phone forKey:@"phone"];
    [params setValue:self.formModel.bd_name forKey:@"realname"];
    [params setValue:self.formModel.bd_idNo forKey:@"idCardNumber"];
    [params setValue:self.formModel.bd_address forKey:@"address"];
    [params setValue:self.formModel.bd_mz forKey:@"nation"];
    [params setValue:self.formModel.bd_gx forKey:@"relations"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KbindRela parameters:params success:^(id  _Nonnull responseObject) {
       DLog(@"%@", [responseObject mj_JSONString])
        HEResponse *response = [HEResponse mj_objectWithKeyValues: responseObject];
        if (response.success) {
            [Dialog toastBottom: @"修改成功"];
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
 
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _sections.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
 
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
    }];
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
    v.backgroundColor = CViewBgColor;
    return v;
}

#pragma mark 解决cell分割线左侧留空的问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 下面这几行代码是用来设置cell的上下行线的位置
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    //按照作者最后的意思还要加上下面这一段，才能做到底部线控制位置，所以这里按stackflow上的做法添加上吧。
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}


@end
